package com.jojo.service;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jojo.entity.Db;
import com.jojo.mapper.DbMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

/**
 * @author JOJO
 * @version 1.0
 * @since 1.8
 */
@Service
public class DbService {

    @Autowired
    private DbMapper dbMapper;

    //更新双色球
    public void updateDbData() {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet("https://datachart.500.com/ssq/history/newinc/history.php?start=3000&end=");
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            HttpEntity responseEntity = response.getEntity();
            Document doc = Jsoup.parse(EntityUtils.toString(responseEntity));
            Elements rows = doc.select("tr[class=t_tr1]");
            for (Element row : rows) {
                String id = row.select("td").get(0).text();
                QueryWrapper<Db> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("id", id);
                List<Db> dblist = dbMapper.selectList(queryWrapper);
                if (dblist.isEmpty()) {
                    Db db = new Db();
                    db.setId(id);
                    db.setRed1(row.select("td[class=t_cfont2]").get(0).text());
                    db.setRed2(row.select("td[class=t_cfont2]").get(1).text());
                    db.setRed3(row.select("td[class=t_cfont2]").get(2).text());
                    db.setRed4(row.select("td[class=t_cfont2]").get(3).text());
                    db.setRed5(row.select("td[class=t_cfont2]").get(4).text());
                    db.setRed6(row.select("td[class=t_cfont2]").get(5).text());
                    db.setBlue1(row.select("td[class=t_cfont4]").get(0).text());
                    dbMapper.insert(db);
                } else {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            assert response != null;
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //双色球选红色球
    public List<String> chooseDbRedBall() {
        List<Db> dblist = dbMapper.selectList(null);
        int lastNumber = Integer.parseInt(dblist.get(dblist.size() - 1).getId());
        int beginNumber = Integer.parseInt(dblist.get(dblist.size() - 51).getId());
        Map<String, Integer> map = new LinkedHashMap<>();
        for (int i = 1; i <= 33; i++) {
            String number = "";
            if (i < 10) {
                number = "0" + i;
            } else {
                number = String.valueOf(i);
            }
            QueryWrapper<Db> queryWrapper = new QueryWrapper<>();
            String finalNumber = number;
            queryWrapper.between("id", beginNumber, lastNumber).and(
                    wq -> wq.eq("red1", finalNumber)
                            .or().eq("red2", finalNumber)
                            .or().eq("red3", finalNumber)
                            .or().eq("red4", finalNumber)
                            .or().eq("red5", finalNumber)
                            .or().eq("red6", finalNumber)
            );
            dblist = dbMapper.selectList(queryWrapper);
            map.put(number, dblist.size());
        }
        map = MapUtil.sortByValue(map, false);
        int i = 0;
        List<String> list = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            if (i >= 11 && i <= 32) {
                list.add(entry.getKey());
            }
            i++;
        }
        return list;
    }

    //双色球选蓝色球
    public List<String> chooseDbBlueBall() {
        List<Db> dblist = dbMapper.selectList(null);
        int lastNumber = Integer.parseInt(dblist.get(dblist.size() - 1).getId());
        int beginNumber = Integer.parseInt(dblist.get(dblist.size() - 51).getId());
        Map<String, Integer> map = new LinkedHashMap<>();
        for (int i = 1; i <= 16; i++) {
            String number = "";
            if (i <= 9) {
                number = "0" + i;
            } else {
                number = String.valueOf(i);
            }
            QueryWrapper<Db> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("blue1", number)
                    .between("id", beginNumber, lastNumber);
            dblist = dbMapper.selectList(queryWrapper);
            map.put(number, dblist.size());
        }
        map = MapUtil.sortByValue(map, false);
        int i = 0;
        List<String> list = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            if (i >= 4 && i <= 15) {
                list.add(entry.getKey());
            }
            i++;
        }
        return list;
    }

    //双色球随机组合
    public LinkedHashMap<Integer, List<String>> composeDb() {
        updateDbData();
        List<String> redList = chooseDbRedBall();
        List<String> blueList = chooseDbBlueBall();
        LinkedHashMap<Integer, List<String>> map = new LinkedHashMap<>();
        List<String> tempBlueList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            int randomInt;
            List<String> list = new ArrayList<>();
            for (int j = 0; j < 6; j++) {
                randomInt = RandomUtil.randomInt(0, 22);
                while (list.contains(redList.get(randomInt))) {
                    randomInt = RandomUtil.randomInt(0, 22);
                }
                list.add(redList.get(randomInt));
            }
            randomInt = RandomUtil.randomInt(0, 12);
            while (tempBlueList.contains(blueList.get(randomInt))) {
                randomInt = RandomUtil.randomInt(0, 12);
            }
            tempBlueList.add(blueList.get(randomInt));
            list = ListUtil.sortByPinyin(list);
            list.add(blueList.get(randomInt));
            map.put(i, list);
        }
        return map;
    }
}
